package com.freedom.monitor.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freedom.monitor.myeye.config.service.ProductConfigService;
import com.freedom.monitor.myeye.config.service.ProductResult;
import com.freedom.monitor.utils.ConstantUtils;
import com.freedom.monitor.utils.CookieUtils;
import com.freedom.monitor.utils.ExclusionStrategyUtils;
import com.freedom.monitor.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.Logger;
import com.freedom.rpc.thrift.common.utils.SocketUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Controller
@RequestMapping(value = "/product")
public class ProductController {
	//
	private static final Logger logger = Logger.getLogger(ProductController.class);

	
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("index for product...");
		return new ModelAndView("product/index", model);// 返回product/index.jsp
	}

	// 查询所有的产品
	@RequestMapping(value = "/query", method = { RequestMethod.GET }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String query(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("ProductController.query invoked...");
		try {
			// 1)先获取type参数
			String page = request.getParameter("page");
			String rows = request.getParameter("rows");
			if (false == StringUtils.valid(page, rows)) {
				page = "1";
				rows = "10";
			}
			int intPage = Integer.parseInt(page.trim());
			int intRows = Integer.parseInt(rows.trim());
			logger.debug("received --->" + "page->" + page + " rows:" + rows);
			String operatorId = (String) CookieUtils.getCookie(request).get(ConstantUtils.COOKIE_USER_ID);
			if (false == StringUtils.valid(operatorId)) {
				throw new Exception("invalid userId,please re login...");
			}
			// 2)尝试获取远程服务结果
			ProductResult result = new ProductResult();
			logger.debug("try to get ConfigService.Client configServiceClient");
			ProductConfigService.Client productServiceClient = (ProductConfigService.Client) SocketUtils
					.getSyncAopObject(ProductConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = productServiceClient.queryProduct(intPage, intRows, operatorId);
			// 拿到了结果
			if (true == result.isSucceed() && result.getProductListSize() >= 0) {
				// 正确且有数据
				Gson gson = new GsonBuilder().setExclusionStrategies(ExclusionStrategyUtils.getInstance()).create();
				String str = "" + "{\"total\":" + result.getTotal() + ","//
						+ "\"rows\":" + gson.toJson(result.getProductList())//
						+ "}";
				logger.debug("" + str);
				return str;
			}
			throw new Exception("query product result is not valid");
		} catch (Exception e) {// 返回空数据
			return "{\"total\":0,\"rows\":[]}";
		}
	}

	// 新增
	@RequestMapping(value = "/addOrUpdate", method = {
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String addOrUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("ProductController.addOrUpdate() invoked...");
		try {
			// 1)获取参数
			String pid = request.getParameter("pid");
			logger.debug("pid---[" + pid + "]");
			String pname = request.getParameter("pname");
			logger.debug("pname---" + pname);
			String pcode = request.getParameter("pcode");
			String pdesc = request.getParameter("pdesc");
			logger.debug("pdesc---" + pdesc);
			String email = request.getParameter("email");
			String mobile = request.getParameter("mobile");
			String createBy = (String) CookieUtils.getCookie(request).get(ConstantUtils.COOKIE_USER_ID);
			if (false == StringUtils.valid(pname, pcode, pdesc, email, mobile)) {
				throw new Exception("invalid parameter...");
			}
			if (false == StringUtils.valid(createBy)) {
				throw new Exception("invalid userId,please re login...");
			}
			// 2)调用远程的程序
			logger.debug("try to get ConfigService.Client configServiceClient");
			ProductConfigService.Client productServiceClient = (ProductConfigService.Client) SocketUtils
					.getSyncAopObject(ProductConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			boolean result = false;
			if (null != pid && pid.trim().length() > 0) {
				logger.debug("action->edit");
				result = productServiceClient.editProduct(pname, pcode, pdesc, email, mobile, pid);
			} else {
				logger.debug("action->add");
				result = productServiceClient.addProduct(pname, pcode, pdesc, email, mobile, createBy);
			}
			// 3)根据结果说话
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}

	// 删除
	@RequestMapping(value = "/del", method = { RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("ProductController.delete invoked...");
		boolean result = false;
		try {
			// 1)先获取id
			String pid = request.getParameter("pid");
			if (false == StringUtils.valid(pid)) {
				throw new Exception("invalid pid--->" + pid);
			}
			logger.debug("received to be delete product id --->" + pid);
			// 2)尝试获取远程服务结果
			logger.debug("try to get ConfigService.Client configServiceClient");
			ProductConfigService.Client productServiceClient = (ProductConfigService.Client) SocketUtils
					.getSyncAopObject(ProductConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = productServiceClient.deleteProduct(pid);
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {// 返回空数据
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}
}
